package com.unittec.zk.provider.auth.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.unittec.zk.provider.auth.entity.SysDic;
import com.unittec.zk.provider.auth.service.SysDicItemService;
import com.unittec.zk.provider.auth.service.SysDicService;
import com.unittec.zk.provider.log.Log;
import com.unittec.zk.provider.utils.CopyUtils;
import com.unittec.zk.provider.utils.ValidationUtils;
import com.unittec.zk.provider.vo.VoCommonResult;
import com.unittec.zk.sdk.auth.domain.SysDicItemDto;
import com.unittec.zk.sdk.auth.domain.SysDicRes;
import com.unittec.zk.sdk.auth.enums.BizErrorCode101;
import com.unittec.zk.sdk.auth.request.Req101601;
import com.unittec.zk.sdk.auth.request.Req101602;
import com.unittec.zk.sdk.auth.request.Req101603;
import com.unittec.zk.sdk.auth.request.Req101604;
import com.unittec.zk.sdk.auth.request.Req101605;
import com.unittec.zk.sdk.auth.request.Req101606;
import com.unittec.zk.sdk.auth.request.Req101614;
import com.unittec.zk.sdk.auth.request.Req101621;
import com.unittec.zk.sdk.auth.response.Res101601;
import com.unittec.zk.sdk.auth.response.Res101602;
import com.unittec.zk.sdk.auth.response.Res101603;
import com.unittec.zk.sdk.auth.response.Res101604;
import com.unittec.zk.sdk.auth.response.Res101605;
import com.unittec.zk.sdk.auth.response.Res101606;
import com.unittec.zk.sdk.auth.response.Res101614;
import com.unittec.zk.sdk.auth.response.Res101621;
import com.unittec.zk.sdk.log.enums.LogOperateEnum;
import com.unittec.zk.sdk.log.enums.LogStatusEnum;
import com.unittec.zk.sdk.root.common.CommonConstant;
import com.unittec.zk.sdk.root.domain.GatewayRequest;
import com.unittec.zk.sdk.root.domain.Result;
import com.unittec.zk.sdk.root.enums.BizCode;
import com.unittec.zk.sdk.root.enums.BizCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author Jason
 * @description 数据字典Controller
 * @date 2019/11/07
 */
@RestController
@Api(tags = "数据字典管理")
public class SysDicController {

    @Autowired
    Log log;

    @Autowired
    SysDicService sysDicService;

    @Autowired
    SysDicItemService sysDicItemService;

    @RequestMapping(value = "/101601", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加字典", notes = "添加字典")
    public Result<Res101601> saveDic(@RequestBody GatewayRequest<Req101601> req) {
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        long startLogTime = System.currentTimeMillis();
        Res101601 res101601 = new Res101601();
        log.debug(req, "saveDic {},param {} ", "begin", JSON.toJSONString(req.getContent()));
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysDic sysDic = new SysDic();
            CopyUtils.copyProperties(req.getContent(), sysDic);
            sysDic.setDelFlag(CommonConstant.DELETE_NO);
            VoCommonResult voCommonResult = sysDicService.saveDic(sysDic);
            if (voCommonResult.getIsSuccess()) {
                res101601.setId(voCommonResult.getPrimaryKey());
                bizCodeEnum = BizCode.SUCCESS;
                log.addOperateLog("101601", JSON.toJSONString(req), "添加字典", "添加字典成功", LogOperateEnum.LOG_ADD.getCode(),
                    LogStatusEnum.SUCCESS.getCode(), startLogTime);
            } else {
                bizCodeEnum = BizCode.ERROR;
                log.addOperateLog("101601", JSON.toJSONString(req), "添加字典", "添加字典失败：" + bizCodeEnum.getCode(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.toString());
        }
        log.debug(req, "saveDic{}  ", "end");

        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101601);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101602", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改字典", notes = "修改字典")
    public Result<Res101602> updateDic(@RequestBody GatewayRequest<Req101602> req) {
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        long startLogTime = System.currentTimeMillis();
        log.debug(req, "updateDic {} ,param {} ", "begin", JSON.toJSONString(req.getContent()));
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysDic sysDic = sysDicService.getDicDetail(req.getContent().getId());
            // 查询数据是否存在
            if (ObjectUtils.isNotNull(sysDic)) {
                VoCommonResult voCommonResult = sysDicService.updateDic(req.getContent(), sysDic);
                if (voCommonResult.getIsSuccess()) {
                    bizCodeEnum = BizCode.SUCCESS;
                    log.addOperateLog("101602", JSON.toJSONString(req), "修改字典", "修改字典成功",
                        LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
                } else {
                    bizCodeEnum = BizCode.ERROR;
                    log.addOperateLog("101602", JSON.toJSONString(req), "修改字典", "添加字典失败：" + bizCodeEnum.getCode(),
                        LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
                }
            } else {
                bizCodeEnum = BizCode.NOT_LIST;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.toString());
        }
        log.debug(req, "updateDic{}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101603", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除字典", notes = "删除字典")
    public Result<Res101603> deleteDic(@RequestBody GatewayRequest<Req101603> req) {
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        long startLogTime = System.currentTimeMillis();
        log.debug(req, "deleteDic {} ,param {} ", "begin", JSON.toJSONString(req.getContent()));
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysDic sysDic = new SysDic();
            sysDic.setId(req.getContent().getId());
            sysDic.setDelFlag(CommonConstant.DELETE_YES);
            boolean ret = sysDicService.updateById(sysDic);
            if (ret) {
                bizCodeEnum = BizCode.SUCCESS;
                log.addOperateLog("101603", JSON.toJSONString(req), "删除字典", "删除字典成功", LogOperateEnum.LOG_DEL.getCode(),
                    LogStatusEnum.SUCCESS.getCode(), startLogTime);
            } else {
                bizCodeEnum = BizCode.ERROR;
                log.addOperateLog("101603", JSON.toJSONString(req), "删除字典", "删除字典失败：" + bizCodeEnum.getCode(),
                    LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.toString());
        }
        log.debug(req, "deleteDic {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101604", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查看字典详情", notes = "查看字典详情")
    public Result<Res101604> getDicDetail(@RequestBody GatewayRequest<Req101604> req) {
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        log.debug(req, "getDicDetail {} ,param {}  ", "begin", JSON.toJSONString(req.getContent()));
        Res101604 res101604 = new Res101604();
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysDic sysDic = sysDicService.getDicDetail(req.getContent().getId());
            if (ObjectUtils.isNotNull(sysDic)) {
                BeanUtils.copyProperties(sysDic, res101604);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.ERROR;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.toString());
        }
        log.debug(req, "getDicDetail {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101604);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101605", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查看字典分页列表", notes = "查看字典分页列表")
    public Result<Res101605> getDicList(@RequestBody GatewayRequest<Req101605> req) {
        log.debug(req, "getDicList{}  ,param {}  ", "begin", JSON.toJSONString(req.getContent()));
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101605 res101605 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            IPage<Map<String, Object>> sysDicList = sysDicService.getDicList(req.getContent());
            res101605 = new Res101605();
            res101605.setPage(sysDicList);
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
        }
        log.debug(req, "getDicList {}  ", "end");

        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101605);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101606", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查看字典不分页", notes = "查看字典列表不分页")
    public Result<Res101606> getDicListNoPage(@RequestBody GatewayRequest<Req101606> req) {
        log.debug(req, "getDicListNoPage{} ,param {}  ", "begin", JSON.toJSONString(req.getContent()));
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101606 res101606 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            List<Map<String, Object>> sysDicListNo = sysDicService.getDicListNoPage(req.getContent());
            res101606 = new Res101606();
            res101606.setObj(sysDicListNo);
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
        }
        log.debug(req, "getDicListNoPage {}  ", "end");

        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101606);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101614", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "数据字典编码唯一性校验", notes = "数据字典编码唯一性校验")
    public Result<Res101614> dicUnique(@RequestBody GatewayRequest<Req101614> req) {
        log.debug(req, "dicUnique{}  ,param {}  ", "begin", JSON.toJSONString(req.getContent()));
        BizCodeEnum bizCodeEnum = BizCode.SUCCESS;
        Res101614 res101614 = new Res101614();
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String id = req.getContent().getId();
            SysDic sysDic = null;
            if (StringUtils.isNotEmpty(id)) {
                sysDic = sysDicService.getDicDetail(id);
            }
            SysDic sysDic2 = sysDicService.dicUnique(req.getContent());

            if (sysDic2 != null) {
                if (sysDic == null) {
                    res101614.setIsSuccess(false);
                } else if (!id.equals(sysDic2.getId())) {
                    res101614.setIsSuccess(false);
                }
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
        }
        log.debug(req, "dicUnique {}  ", "end");

        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101614);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    /**
     * 设备分类查询
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/101621", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "根据字典code查询", notes = "根据字典code查询")
    @ResponseBody
    public Result<Res101621> findByDicCode(@RequestBody GatewayRequest<Req101621> req) {
        log.debug(req, "findByDicCode {}  ", "begin");
        try {
            Req101621 content = req.getContent();
            ValidationUtils.validateEntityStr(content);
            Res101621 res = new Res101621();
            SysDic byDicCode = sysDicService.getByDicCode(content.getDicCode());
            SysDicRes sysDicRes = new SysDicRes();
            if (byDicCode == null) {
                return Result.error(req, "code不存在");
            }
            CopyUtils.copyProperties(byDicCode, sysDicRes);
            List<SysDicItemDto> dicItemListByDicCode = sysDicItemService.findDicItemListByDicCode(content.getDicCode());
            sysDicRes.setItemList(dicItemListByDicCode);
            res.setObj(sysDicRes);
            log.debug(req, "findByDicCode {}  ", "end-------");
            return Result.success(req, res);
        } catch (Exception e) {
            log.error(req, BizErrorCode101.LIST_ERROR.getMessage(), e);
            return Result.error(req, BizErrorCode101.LIST_ERROR.getCode(), BizErrorCode101.LIST_ERROR.getMessage());
        }
    }

}
